package club.qweqwe.dao.impl;

import club.qweqwe.dao.DAO;
import club.qweqwe.utils.ReflectUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.sql.*;
import java.util.List;

public class NewBasicDaoImpl<T> extends DAO<T> {

    public NewBasicDaoImpl(DataSource dataSource) {
        this.dataSource = dataSource;
        this.runner = new QueryRunner(this.dataSource);
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    protected DataSource dataSource;
    protected QueryRunner runner;

    @Override
    public int update(String sql, Object... objects) {
        try {
            return runner.update(sql, objects);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public T query(String sql, Object... objects) {
        try {
            Class clazz = ReflectUtils.getSuperGenericType(this.getClass());
            return runner.query(sql, new BeanHandler<T>(clazz), objects);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int insert(String sql, Object... objects) {
        return update(sql, objects);
    }

    @Override
    public int delete(String sql, Object... objects) {
        return update(sql, objects);
    }

    @Override
    public List<T> querySet(String sql, Object... objects) {
        try {
            Class clazz = ReflectUtils.getSuperGenericType(this.getClass());
            return runner.query(sql, new BeanListHandler<T>(clazz), objects);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
